package com.kaifamiao.tracking.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/cookie/receive/*")
public class CookieReceiveServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 通过请求头中的cookie字段获得由客户端回传的所有cookie信息
        String cookie = request.getHeader( "cookie" );
        System.out.println( "cookie => " + cookie );

        // 获得所有cookie组成的数组
        Cookie[] cookies = request.getCookies();

        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();

        if( cookies != null && cookies.length != 0 ) {
            for ( Cookie ck : cookies ) {
                String name = ck.getName();
                String value = ck.getValue();
                value = URLDecoder.decode( value, StandardCharsets.UTF_8 );
                System.out.printf( "%s : %s\n", name, value );
                out.printf( "<p>%s : %s</p>\n", name, value );
            }
        } else {
            out.printf( "<p>没有接收到cookie</p>\n" );
        }

    }

}
